package com.destroyer.common.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * 多线程任务
 */
public class WorkerThreadPool<T, E> {
    final int size;
    final PoolBack<T, E> poolBack;

    public static interface PoolBack<T, E> {
        T onFuncBack(E e);
    }

    public static <T, E> WorkerThreadPool<T, E> build(PoolBack<T, E> poolBack) {
        return new WorkerThreadPool<>(10, poolBack);
    }

    public static<T, E> WorkerThreadPool<T, E> build(int size, PoolBack<T, E> poolBack) {
        return new WorkerThreadPool<>(size, poolBack);
    }

    public WorkerThreadPool(int size, PoolBack<T, E> poolBack) {
        this.size = size;
        this.poolBack = poolBack;
    }

    public List<T> doWithList(List<E> tasks) {
        // 创建一个大小为10的线程池
        ExecutorService executor = Executors.newFixedThreadPool(size);

        List<Future<T>> futures = new ArrayList<>();

        // 提交每个任务到线程池
        for (E task : tasks) {
            Future<T> future = executor.submit(new TaskProcessor(task));
            futures.add(future);
        }

        List<T> results = new ArrayList<>();

        // 获取所有任务的结果
        for (Future<T> future : futures) {
            try {
                results.add(future.get());  // 注意，future.get()方法可能会阻塞
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
                // 处理异常情况，比如可以为results添加一个默认的VO或者忽略异常
            }
        }

        // 关闭线程池
        executor.shutdown();

        return results;
    }

    public class TaskProcessor implements Callable<T> {
        private final E task;

        public TaskProcessor(E task) {
            this.task = task;
        }

        @Override
        public T call() throws Exception {
            return poolBack.onFuncBack(task);
        }
    }
}
